package com.etrans.web.gps.business.report.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.evidence.service.PictureService;
import com.etrans.web.gps.business.gis.domain.Track;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.timer.LocalCache;
import com.etrans.web.gps.util.AlarmKindUtil;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.grid.FlexiGridUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * 报警综合分析
 * @author jw.chen
 *
 */
@Controller
@RequestMapping("/report/alarmSyn/*")
public class AlarmSynAnalyController extends BaseController{
	
	private final static Logger logger = LoggerFactory.getLogger(AlarmSynAnalyController.class);
	
//	@Autowired
//	private AlarmSynAnalyService alarmSynService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private AlarmKindUtil alarmKindUtil;
	
	@Autowired
	private PictureService pictureService;
	
	/**
	 * 页面跳转入口
	 * @return
	 */
	@RequestMapping(value="getAlarmSynAnalysis.html")
	public ModelAndView getAlarmSynAnalysis(Model model){
		ModelAndView mv =new ModelAndView();
		mv.addObject("flag", false);
		mv.setViewName("views/business/report/alarmSynAnalysis");
		return mv;
		
	}
	@RequestMapping(value="toAlarmSynAnalysis.html")
	public ModelAndView toAlarmSynAnalysis(Model model){
		ModelAndView mv =new ModelAndView();
		mv.addObject("flag", true);
		mv.setViewName("views/business/report/alarmSynAnalysis");
		return mv;
		
	}
	/**
	 * 查询登录用户权限下的全部车辆
	 * @return  车辆id和车牌号
	 */
	@ResponseBody
	@RequestMapping(value = "queryVehicleListByRole.html")
	public List<HashMap<String,Object>> queryVeListByRole(){
		SysUser user = getSysUser();
		HashMap<String,Object> param = new HashMap<String, Object>();
		param.put("fullID", user.getFullID());
		param.put("selected", "selected");
		return commonService.queryVeListByRole(param);
	}
	
	
	/**
	 * 查询权限下所有司机
	 * @return
	 */
	@RequestMapping(value = "loadDriverListByRole.html")
	@ResponseBody
	public List<HashMap<String, Object>> loadDriverListByRole(HttpServletRequest request) {
		String name = request.getParameter("name");
		HashMap<String, Object> param = new HashMap<>();
		SysUser user=getSysUser();
		param.put("FullID", String.format("%08d", user.getArea_id()));
		param.put("name", name);
		param.put("selected", "selected");
		return commonService.queryDriverListByRole(param);
	}
	
	/**
	 * 查询登录用户权限下的平台和业户
	 * @return  
	 */
	@ResponseBody
	@RequestMapping(value = "queryEntAndPlatByRole.html")
	public List<HashMap<String,Object>> queryEntAndPlatByRole(HttpServletRequest request){
		SysUser user = getSysUser();
		Integer area_id = user.getArea_id();
		String name = request.getParameter("name");
		String plat = request.getParameter("plat");
		List<HashMap<String, Object>> list ;
		if (StringUtils.isEmpty(plat)) {
			list = commonService.queryEnterAndPlatByRole(area_id,name);
		}else {
			list = commonService.queryPlatByRole(area_id, name);
		}		
		return list;
	}
	
	/**
	 * 查询平台维度(柱状图和折线图)
	 * @return 
	 */
	@ResponseBody
	@RequestMapping(value = "getChartData.html")
	public HashMap<String,Object> getChartData(String queryType,String queryContent, String startDate, String endDate){
		try {
			String filter = "";
			String table = "";
			if("0".equals(queryType)){
				filter = "gnss_centerid";
				table = "platform_swap";
			}else if("1".equals(queryType)){
				filter = "enterprise_id";
				table = "enterprise_swap";
			}else if("2".equals(queryType)){
				filter = "vehicle_no";
				table = "vehicle_swap";
			}else if("3".equals(queryType)){
				filter = "licence";
				table = "driver_alarm_swap";
			}
			Date start = DateUtil.getISODate(startDate);
			Date end = DateUtil.getISODate(endDate);
			
			List<Bson> bson = new ArrayList<>();
			// 查询条件
			DBObject match = new BasicDBObject();
			//查询全部，不过滤平台
			if(StringUtils.isNotBlank(queryContent)){
				if("0".equals(queryType) || "1".equals(queryType)){
					match.put(filter, Integer.parseInt(queryContent));
				}else{
					match.put(filter, queryContent);
				}
			}
			
			DBObject date = new BasicDBObject();
			date.put("$gte", start);
			date.put("$lte", end);
			match.put("analyse_date", date);
			Bson matchField = new BasicDBObject("$match", match);
			
			//根据报警类型分组
			DBObject groupFields = new BasicDBObject();
			//查询全部，不按平台分组
			if(queryContent != null && !"".equals(queryContent)){
				groupFields.put("_id", "$"+filter);
			}else{
				groupFields.put("_id", new ObjectId());
			}
			
			DBObject overspeed_count = new BasicDBObject();
			overspeed_count.put("$sum", "$overspeed_count");
			groupFields.put("overspeed_count", overspeed_count);
			DBObject roadoffset_count = new BasicDBObject();
			roadoffset_count.put("$sum", "$roadoffset_count");
			groupFields.put("roadoffset_count", roadoffset_count);
			DBObject tired_count = new BasicDBObject();
			tired_count.put("$sum", "$tired_count");
			groupFields.put("tired_count", tired_count);
			DBObject nightly_3rd_count = new BasicDBObject();
			nightly_3rd_count.put("$sum", "$nightly_3rd_count");
			groupFields.put("nightly_3rd_count", nightly_3rd_count);
			DBObject prohibit_driving_count = new BasicDBObject();
			prohibit_driving_count.put("$sum", "$prohibit_driving_count");
			groupFields.put("prohibit_driving_count", prohibit_driving_count);
			Bson group = new BasicDBObject("$group", groupFields);
			
			// 先匹配后分组再统计
			bson.add(matchField);
			bson.add(group);
			//柱状图数据
			List<Object> barList = MGTemplete.aggregate("egov", table, bson);
			
			//根据分析时间分组
			groupFields.put("_id", "$analyse_date");	//替换分组id
			//按时间倒序
			DBObject sortField = new BasicDBObject();
			sortField.put("_id", Constant.MONGODB_ASC);
			Bson sort = new BasicDBObject("$sort", sortField);
			bson.add(sort);
			//折线图数据
			List<Object> lineList = MGTemplete.aggregate("egov", table, bson);
			
			HashMap<String,Object> map = new HashMap<String, Object>();
			map.put("barList", barList);
			map.put("lineList", lineList);
			return map;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 点击柱状图关联折线图数据
	 * @return 
	 */
	@ResponseBody
	@RequestMapping(value = "getLineChartData.html")
	public List<Object> getLineChartData(String queryType,String queryContent, String alarmType, String startDate, String endDate){
		try {
			String filter = "";
			String table = "";
			if("0".equals(queryType)){
				filter = "gnss_centerid";
				table = "platform_swap";
			}else if("1".equals(queryType)){
				filter = "enterprise_id";
				table = "enterprise_swap";
			}else if("2".equals(queryType)){
				filter = "vehicle_no";
				table = "vehicle_swap";
			}else if("3".equals(queryType)){
				filter = "licence";
				table = "driver_alarm_swap";
			}
			Date start = DateUtil.getISODate(startDate);
			Date end = DateUtil.getISODate(endDate);
			
			List<Bson> bson = new ArrayList<>();
			// 查询条件
			DBObject match = new BasicDBObject();
			//查询全部，不过滤平台
			if(queryContent != null && !"".equals(queryContent)){
				match.put(filter, Integer.parseInt(queryContent));
			}
			
			DBObject date = new BasicDBObject();
			date.put("$gte", start);
			date.put("$lte", end);
			match.put("analyse_date", date);
			Bson matchField = new BasicDBObject("$match", match);
			
			//根据报警类型分组
			DBObject groupFields = new BasicDBObject();
			//根据分析时间分组
			groupFields.put("_id", "$analyse_date");	
			
			if("overspeed".equals(alarmType)){
				DBObject overspeed_count = new BasicDBObject();
				overspeed_count.put("$sum", "$overspeed_count");
				groupFields.put("overspeed_count", overspeed_count);
			}
			if("roadoffset".equals(alarmType)){
				DBObject roadoffset_count = new BasicDBObject();
				roadoffset_count.put("$sum", "$roadoffset_count");
				groupFields.put("roadoffset_count", roadoffset_count);
			}
			if("tired".equals(alarmType)){
				DBObject tired_count = new BasicDBObject();
				tired_count.put("$sum", "$tired_count");
				groupFields.put("tired_count", tired_count);
			}
			if("nightly_3rd".equals(alarmType)){
				DBObject nightly_3rd_count = new BasicDBObject();
				nightly_3rd_count.put("$sum", "$nightly_3rd_count");
				groupFields.put("nightly_3rd_count", nightly_3rd_count);
			}
			if("prohibit_driving".equals(alarmType)){
				DBObject prohibit_driving_count = new BasicDBObject();
				prohibit_driving_count.put("$sum", "$prohibit_driving_count");
				groupFields.put("prohibit_driving_count", prohibit_driving_count);
			}
			Bson group = new BasicDBObject("$group", groupFields);
			//按时间倒序
			DBObject sortField = new BasicDBObject();
			sortField.put("_id", Constant.MONGODB_ASC);
			Bson sort = new BasicDBObject("$sort", sortField);
			bson.add(sort);
			
			// 先匹配后分组再统计
			bson.add(matchField);
			bson.add(group);
			
			//折线图数据
			List<Object> lineList = MGTemplete.aggregate("egov", table, bson);
			
			return lineList;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 点击柱状图关联表格数据
	 * @return 
	 */
	@ResponseBody
	@RequestMapping(value = "getTableChartData.html")
	public PageVo getTableChartData(String paramsGrid){
		try {
			Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
			String startDate = String.valueOf(params.get("startDate"));				//开始时间
			String endDate = String.valueOf(params.get("endDate"));					//结束时间
			String alarmType = String.valueOf(params.get("alarmType"));				//报警类型
			String queryType = String.valueOf(params.get("queryType"));				//查询方式
			String queryContent = String.valueOf(params.get("queryContent"));		//查询内容
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start = sdf.parse(startDate);
			Date end = sdf.parse(endDate);
			
			int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
			int page = Integer.parseInt(String.valueOf(params.get("page")));
			
			HashMap<String, Object> whereMap = new HashMap<String, Object>();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("$gte", start);
			param.put("$lte", end);
			whereMap.put("alarm_time", param);
			if(!"null".equals(alarmType) && !"".equals(alarmType)){
				whereMap.put("alarm_type", alarmKindUtil.getAlarmKind(alarmType));
			}else{
				Integer[] alarm_type = alarmKindUtil.getAlarmKindInt();
				param = new HashMap<String, Object>();
				param.put("$in", alarm_type);
				whereMap.put("alarm_type", param);
			}
			
			if(!"".equals(queryContent) && !"null".equals(queryContent)){
				if(queryType != null && "0".equals(queryType)){
					whereMap.put("gnsscenter_id", Integer.parseInt(queryContent));
				}
				if(queryType != null && "1".equals(queryType)){
					whereMap.put("enterprise_id", Integer.parseInt(queryContent));
				}
				if(queryType != null && "2".equals(queryType)){
					whereMap.put("vehicle_no", queryContent);
				}
				if(queryType != null && "3".equals(queryType)){
					whereMap.put("licence", queryContent);
				}
			}
			HashMap<String, Object> sortMap = new HashMap<String,Object>();
			sortMap.put("alarm_time", Constant.MONGODB_DESC);
			
			Long total = MGTemplete.findCount("egov", "alarm_result", whereMap);
			List<Document> list = MGTemplete.find("egov", "alarm_result", whereMap,sortMap,page,pageSize);
			Map<Integer, String> ent_map = LocalCache.entMap;
			Map<Integer, String> platMap = LocalCache.platMap;
			for (Document document : list) {
				document.put("alarm_time", sdf.format(document.getDate("alarm_time")));
				//获取业户和平台名称
				Integer enterprise_id = (int)document.get("enterprise_id");
				Integer platform_id = (int)document.get("platform_id");
				if(ent_map != null && ent_map.size() > 0){
					document.put("enterprise_name", ent_map.get(enterprise_id));
				}
				if(platMap != null && platMap.size() > 0){
					document.put("platform_name", platMap.get(platform_id));
				}
				
				Integer alarm_type = (int)document.get("alarm_type");
				document.put("alarm_type", alarmKindUtil.getAlarmKindName(alarm_type));
				document.put("alarm_type_id", alarm_type);
				
				Document doc = (Document) document.get("coordinates");
				if(doc != null){
					List coordinates = (List) doc.get("coordinates");
					document.put("lng", coordinates.get(0));
					document.put("lat", coordinates.get(1));
					document.remove(coordinates);
				}
				
				//处警结果暂时拿第一条
				List<Document> historys = (List<Document>) document.get("history");
				if(historys != null && historys.size() > 0){
					Document history = historys.get(historys.size()-1);
					if(history != null){
						document.put("handle_time", history.get("rcv_time"));
						document.put("handle_result", "已处理");
					}
				}
			}
			
			PageVo pageVo = new PageVo();
			pageVo.setTotal(total.intValue());
			pageVo.setRows(list);
			pageVo.setPage(page);
			return pageVo;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@RequestMapping(value = "toVehiclePosition.html")
	public String toVehiclePosition(Model model) throws Exception{
		return "views/business/report/vehiclePosition";
	}
	
	@RequestMapping(value = "vehiclePosition.html")
	public String vehiclePosition(HttpServletResponse response) throws Exception{
		HashMap<String,Object> params = this.getReqParameters();
		String vehicle_no_color = (String) params.get("vehicle_no_color");
		Long alarm_time = Long.valueOf((String) params.get("alarm_time"));
		double lng = params.get("lng") == null ? 0 : Double.parseDouble((String) params.get("lng"));
		double lat = params.get("lat") == null ? 0 : Double.parseDouble((String) params.get("lat"));
		
		Map<String,Object> result = new HashMap<>();
		Track track = new Track();
		if(vehicle_no_color != null && !"".equals(vehicle_no_color)){
			String no_color = vehicle_no_color.split(",")[0];
			track.setVehicleNo(no_color.split("_")[0]);
			track.setVehicleColor(Integer.parseInt(no_color.split("_")[1]));
			track.setAlarmTime(alarm_time);
			track.setLongitude(lng);
			track.setLatitude(lat);
		}
		result.put("data", track);
		this.ajaxResultJson(response, result);
		return null;
	}
	
	/**
	 * 获取到adas处警的图片、视频等
	 * @return 
	 */
	@ResponseBody
	@RequestMapping(value = "getAdasMaterial.html")
	public String getAdasMaterial(HttpServletResponse response,HttpServletRequest request){
		HashMap<String,Object> params = this.getReqParameters();
		
		try {
			String vehicleNo=params.get("vehicle_no").toString();
			long alarm_time=Long.parseLong(params.get("alarm_time").toString());
			
			SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String d = sdf.format(alarm_time); 
			Date gpsTime = sdf.parse(d);
			
			Map<String,Object> result = new HashMap<>();			
			result.put("data", pictureService.queryPictureByVehicleNoAndTime(vehicleNo, gpsTime));			
			this.ajaxResultJson(response, result);
		} catch (ParseException e) {
			logger.error("获取adas证据失败");
			e.printStackTrace();
		}
		
		return null;
	}
	
}
